<?php

namespace Core\Common\Handler;

use Core\Common\Base\Log;
use Core\Common\Util\Helper;

/**
 * Description of Monitor
 *
 * @author baiyang@ibantang.com
 */
class MonitorHandler
{
    private static $masterId = null;
    private static $managerId = null;
    private static $online = false;

    public static function run(\swoole_server $server)
    {
        if (is_null(self::$masterId)) {
            self::$masterId = (int)file_get_contents(CORE_PID_DIR . 'master');
        }
        if (is_null(self::$managerId)) {
            self::$managerId = (int)file_get_contents(CORE_PID_DIR . 'manager');
        }
        if (!self::$online) {
            self::$online = time();
            self::notify();
        }
        //是否输出服务的当前连接数，做监控; 没有配置stats或者stats不为false, 则输出
        if (!isset($server->setting['stats']) || !empty($server->setting['stats'])) {
            $now = time();
            if ($now - self::$online > 0) {
                $prefix = 'php,service=' . CORE_NAME ;
                $time = number_format(microtime(true) * 1000000000, 0, '', '');
                $metrics = ' conn=' . $server->stats()['connection_num']
                . ',wait=' . $server->stats()['tasking_num'];
                $str = $prefix . $metrics . ' ' . $time;
                Log::save('php', $str."\n", 'influx_');
                self::$online = $now;
            }
        }
        $lockfile = CORE_PID_DIR . 'lock';
        if (file_exists($lockfile)) {
            $lockPid = (int)file_get_contents($lockfile);
            if ($lockPid == posix_getpid()) {
                return;
            }
            if (\swoole_process::kill($lockPid, 0)) {
                posix_kill($lockPid, SIGKILL);
            }
            unlink($lockfile);
        }
        $masterAlive = \swoole_process::kill(self::$masterId, 0);
        sleep(1);
        if ($masterAlive) {
            return;
        }
        file_put_contents($lockfile, posix_getpid(), LOCK_EX);
        $response = [];
        exec('( /bin/bash '.CORE_WORK_ROOT.'bin/swoole.sh start && /bin/kill -TERM '.self::$managerId.' & )', $response);
        Log::error(LOG_ERR, [
            'message' => 'master: ' . self::$masterId . ' die',
            'manager' => 'manager: ' . self::$managerId,
            'response' => $response,
            'shell' => '( /bin/bash '.CORE_WORK_ROOT.'bin/swoole.sh start & )'
        ]);
    }

    private static function notify($isOnline = true)
    {
        if (!defined('CORE_ENV') || !in_array(CORE_ENV, ['beta', 'release', 'product', 'prod'])) {
            return;
        }
        $flag = '上线成功';
        if (!$isOnline) {
            $flag = '下线成功';
        }
        $url = 'https://oapi.dingtalk.com/robot/send?access_token=067b59a02cd804299a4e64dfb776d627006f731c7f3375e671019d917ef2a481';
        $ch = curl_init();
        $msgArr = [
            '服务: ' . CORE_NAME,
            '主机: ' . Helper::getHostName(),
            '环境: ' . CORE_ENV,
            '用户: ' . Helper::getCurrentUser(),
        ];
        $data = [
            'msgtype' => 'text',
            'text' => [
                'content' => implode("\n", $msgArr)."\n$flag\n",
            ],
            'at' => [
                'isAtAll' => false,
            ],
        ];
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HEADER => false,
            CURLOPT_TIMEOUT_MS => 1000,
            CURLOPT_URL => $url,
            CURLOPT_POSTFIELDS => json_encode($data),
            CURLOPT_POST => true,
            CURLOPT_HTTPHEADER => [
                'Content-Type: ' .'application/json; charset=utf-8',
            ],
        ]);
        curl_exec($ch);
    }
}
